<template>
  <div>
    <div class="bucket">名称: {{ bucket.name }}  编号: {{ bucket.bucketNumber }}</div>
    <el-row style="padding: 0 5px;">
      <el-col :span="12" v-for="(videoSrc, index) in videoList" :key="index">
        <div class="video-container" @click="selectVideo(index)">
          <video
            :ref="'videos'"
            :class="{ 'selected': selectedVideoIndex === index }"
            controls
            autoplay
            muted
          ></video>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Hls from 'hls.js';
import { getVideo, getBucket } from "@/api/system/resource";

export default {
  name: 'VideoPlayer',
  data() {
    return {
      videoList: [],
      bucket: {},
      selectedVideoIndex: null, // 记录选中的视频索引
    };
  },
  methods: {
    selectVideo(index) {
      this.selectedVideoIndex = index; // 更新选中的视频索引
    },
  },
  mounted() {
    const query = this.$route.query;
    if (query && query.id) {
      getBucket(query.id).then(response => {
        if (response.code === 200) {
          this.bucket = response.data;
        }
      });

      getVideo(query.id).then(response => {
        if (response.code === 200) {
          this.videoList = response.data;
          this.$nextTick(() => {
            this.videoList.forEach((videoSrc, index) => {
              const videoUrl = videoSrc.replace(/^http:\/\/120\.238\.96\.5:8890/, '/another-api');
              const video = this.$refs.videos[index];
              if (video) {
                if (Hls.isSupported()) {
                  const hls = new Hls();
                  hls.loadSource(videoUrl);
                  hls.attachMedia(video);
                  hls.on(Hls.Events.MANIFEST_PARSED, () => {
                    video.play().catch(error => {
                      console.warn('Play failed:', error);
                    });
                  });
                } else if (video.canPlayType('application/vnd.apple.mpegURL')) {
                  video.src = videoUrl;
                  video.addEventListener('loadedmetadata', () => {
                    video.play().catch(error => {
                      console.warn('Play failed:', error);
                    });
                  });
                }
              }
            });
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.bucket {
  text-align: center;
  margin-top: 5px;
}

.video-container {
  width: 100%;
  height: 45vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px;
}

video {
  width: 100%;
  height: auto;
  max-height: 100%;
  object-fit: fill;
  border: 1px solid rgb(53, 53, 53);
  transition: border-color 0.3s;
}

video.selected {
  border-color: rgb(0, 255, 2);
}
</style>
